package com.jl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.shiro.ShiroUser;
import com.jl.commons.utils.BASE64;
import com.jl.commons.utils.TimeUtils;
import com.jl.model.InspectionTask;
import com.jl.service.IInspectionTaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 江剑
 */
@Controller
@RequestMapping("/inspectionTask")
public class InspectionTaskController extends BaseController {

    @Autowired
    private IInspectionTaskService inspectionTaskService;

    @GetMapping("/inspectionTaskDataGrid")
    @RequiresPermissions("/inspectionTask/inspectionTaskDataGrid")
    public String inspectionTaskList(){
        return "inspectionTask_list";
    }

    @GetMapping("/detail")
    @RequiresPermissions("/inspectionTask/detail")
    public String inspectionTaskDetail(ModelMap mp, Long id){
        mp.put("id",id);
        return "inspectionTask_detail";
    }


    @GetMapping("/addComment")
    public String addCommentPage(ModelMap mp, Long id,Integer type){
        mp.put("id",id);
        mp.put("type",type);
        return "addInspectionComment";
    }

    @PostMapping("/addComment")
    @ResponseBody
    public ResultData addComment(Long id,String comment,Integer status,Integer type){
        InspectionTask inspectionTask = new InspectionTask();
        inspectionTask.setId(id);
        inspectionTask.setStatus(status);
        inspectionTask.setGmtModified(new Date());
        ShiroUser shiroUser = getShiroUser();
        inspectionTask.setModifyId(shiroUser.getId());
        if(type.equals(1)){
//           班长 1
            inspectionTask.setMonitorComment(comment);
            inspectionTask.setMonitorId(shiroUser.getId());
            inspectionTask.setMonitorName(shiroUser.getUsername());
        }else{
//            主管 2
            inspectionTask.setDirectorComment(comment);
            inspectionTask.setDirectorId(shiroUser.getId());
            inspectionTask.setDirectorName(shiroUser.getUsername());
        }
        inspectionTaskService.updateById(inspectionTask);
        return success();
    }

    @GetMapping("/addResult")
    public String addResultPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "addInspectionTaskResult";
    }

    @PostMapping("/getInspectionTask")
    @ResponseBody
    public ResultData getResult(Long id){
       InspectionTask inspectionTask = inspectionTaskService.getById(id);
       return success(inspectionTask);
    }

    @PostMapping("/addResult")
    @ResponseBody
    public ResultData addResult(Long id,String result){
//        只有插入了执行结果才能算执行完成。
        Long operatorId = getUserId();
        if(inspectionTaskService.updateInspectionTaskResult(id,operatorId,result)){
            return success();
        }
        return fail();
    }

    @GetMapping("/add")
    @RequiresPermissions("/inspectionTask/add")
    public String addInspectionTaskPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "inspectionTask_add";
    }


    @PostMapping("/add")
    @RequiresPermissions("/inspectionTask/add")
    @ResponseBody
    public ResultData addInspectionTask(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        InspectionTask inspectionTask = JSON.parseObject(value,InspectionTask.class);
        Date now =new Date();
        inspectionTask.setName(inspectionTask.getName()+"-"+ TimeUtils.parseDateToStr(now,"YYYY年MM月dd日"));
        inspectionTask.setIsTemp(Constants.IS_TEMP_TASK);
            //新增数据
        inspectionTask.setCreateId(getUserId());
        inspectionTask.setGmtCreate(now);
        inspectionTaskService.save(inspectionTask);
        return success(inspectionTask);
    }


    @GetMapping("/edit")
    @RequiresPermissions("/inspectionTask/edit")
    public String editInspectionTaskPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "inspectionTask_add";
    }

    @PostMapping("/edit")
    @RequiresPermissions("/inspectionTask/edit")
    @ResponseBody
    public ResultData editInspectionTask(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        InspectionTask inspectionTask = JSON.parseObject(value,InspectionTask.class);
        Date now =new Date();
        inspectionTask.setName(inspectionTask.getName()+"-"+ TimeUtils.parseDateToStr(now,"YYYY年MM月dd日 HH:mm:ss"));
        inspectionTask.setGmtModified(now);
        inspectionTask.setModifyId(getUserId());

        inspectionTaskService.updateById(inspectionTask);
        return success(inspectionTask);
    }

    @PostMapping("/delete")
    @RequiresPermissions("/inspectionTask/delete")
    @ResponseBody
    public ResultData deletesInspectionTask(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        List<Long> ids = JSONArray.parseArray(value,Long.class);
        boolean b = inspectionTaskService.removeByIds(ids);
        if(b){
            return success();
        }
        return fail();
    }

    @PostMapping("/dataGrid")
    @RequiresPermissions("/inspectionTask/dataGrid")
    @ResponseBody
    public ResultData inspectionTaskDataGrid(Long current,Long pageSize,String searchCol,String searchValue,String json){
        if(current == null || pageSize == null){
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        QueryWrapper<InspectionTask> queryWrapper = new QueryWrapper<>();

        if(StringUtils.isNotBlank(json)){
            String value = BASE64.decode(json);
            JSONObject jsonObject = JSONObject.parseObject(value);
            if(StringUtils.isNotBlank(jsonObject.getString("name"))){
                queryWrapper.like("t.name",jsonObject.getString("name"));
            }
            if(null!=jsonObject.getInteger("status") && jsonObject.getInteger("status")!=0){
                queryWrapper.eq("t.status",jsonObject.getString("status"));
            }
            if(null!=jsonObject.getLong("modelId") && jsonObject.getLong("modelId")!=0){
                queryWrapper.eq("t.model_id",jsonObject.getString("modelId"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("finishTime"))){
                queryWrapper.like("t.finish_time",jsonObject.getString("finishTime"));
            }
            if(null!=jsonObject.getLong("operatorId") && jsonObject.getLong("operatorId")!=0){
                queryWrapper.eq("t.operator_id",jsonObject.getString("operatorId"));
            }
            // 查询所有非故障产生的巡检任务
            queryWrapper.ne("t.is_temp",Constants.FAULT_TASK);
        }else{
//            如果有查询列且查询列为id 则 表示直接通过id查询
            if(searchCol.equals(Constants.ID) && StringUtils.isNotBlank(searchValue)){
                queryWrapper.eq("t.id",searchValue);
            }else{
                if(StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)){
                    queryWrapper.like("t."+searchCol,searchValue);
                }
                // 查询所有非故障产生的巡检任务
                queryWrapper.ne("t.is_temp",Constants.FAULT_TASK);
            }
        }
        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        inspectionTaskService.selectInspectionTaskDataGrid(pageDataInfo,queryWrapper);
        return success(pageDataInfo);
    }


    @GetMapping("/faultInspectionTask")
    @RequiresPermissions("/inspectionTask/faultInspectionTask")
    public String faultInspectionTaskPage(){
        return "faultTask_list";
    };
    /**
     * 这里只查询是由故障信息导入的检查任务
     * @return
     */
    @PostMapping("/faultInspectionTask")
    @RequiresPermissions("/inspectionTask/faultInspectionTask")
    @ResponseBody
    public ResultData faultInspectionTask(Long current,Long pageSize,String searchCol,String searchValue,String json){
        if(current == null || pageSize == null){
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        QueryWrapper<InspectionTask> queryWrapper = new QueryWrapper<>();
//        查询所有的由故障产生的巡检任务
        queryWrapper.eq("t.is_temp",Constants.FAULT_TASK);
        //目前的查询只有单表
        if(StringUtils.isNotBlank(json)){
            String value = BASE64.decode(json);
            JSONObject jsonObject = JSONObject.parseObject(value);
            if(null!=jsonObject.getLong("modelId") && jsonObject.getLong("modelId")!=0){
                queryWrapper.eq("t.model_id",jsonObject.getString("modelId"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("finishTime"))){
                queryWrapper.like("t.finish_time",jsonObject.getString("finishTime"));
            }
            if(null!=jsonObject.getLong("operatorId") && jsonObject.getLong("operatorId")!=0){
                queryWrapper.eq("t.operator_id",jsonObject.getString("operatorId"));
            }

            if(StringUtils.isNotBlank(jsonObject.getString("name"))){
                queryWrapper.like("t.name",jsonObject.getString("name"));
            }
            if(null!=jsonObject.getInteger("status") && jsonObject.getInteger("status")!=0){
                queryWrapper.eq("t.status",jsonObject.getString("status"));
            }
        }else{
            if(StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)){
                if(searchCol.equals(Constants.ID)){
                    queryWrapper.eq("t.id",searchValue);
                }else{
                    queryWrapper.like("t."+searchCol,searchValue);
                }
            }
        }
        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        inspectionTaskService.selectInspectionTaskDataGrid(pageDataInfo,queryWrapper);
        return success(pageDataInfo);
    }

}